package com.quanquan.store.message;

import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.service.CouponService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 功能描述:给用户发送优惠券的队列
 *
 * @ClassName: MqSendCouponReceiver
 * @Author: xiaoqianh丶
 * @Date: 2019-04-05 23:02
 * @Version: V1.0
 */
@Slf4j
@Component
public class MqSendCouponReceiver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CouponService couponService;

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "sendCoupon",
                    durable = "true"),
            exchange = @Exchange(value = "coupon.exchange",
                    type = "topic"),
            ignoreDeclarationExceptions = "true",
            key = "coupon.#")})
    @RabbitHandler
    public void checkSignContinuous(@Payload String msg,
                                    Channel channel,
                                    @Headers Map<String, Object> headers) throws IOException {
        //会员id
        List<String> userIds = (List<String>) (headers.get("userIds"));
        //连续签到积分奖励数
        Integer count = Integer.parseInt(Objects.requireNonNull(headers.get("coupomNum")).toString());
        //连续签到天数
        List<String> coupomIds = (List<String>) (headers.get("coupomIds"));
        System.out.println(coupomIds);
        System.out.println(userIds);
        //手工ack
        long deliveryTag = Long.parseLong(Objects.requireNonNull(headers.get(AmqpHeaders.DELIVERY_TAG)).toString());
        channel.basicAck(deliveryTag, false);

        for (String userId : userIds) {
            CouponRequest couponRequest = new CouponRequest();
            couponRequest.setCount(count);
            couponRequest.setUserId(userId);
            couponRequest.setSendRequestType(1);
            for (String couponId : coupomIds) {
                couponRequest.setId(couponId);
            }

            couponService.sendCoupon(couponRequest);
        }

    }

}